package helpers;

import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class EmailHelper {
	
	private static final Logger log = Logger.getLogger(EmailHelper.class.getName());
	
	public static void sendMail(String subject, String body, String fromEmail, String toEmail) {
		log.setLevel(Level.FINE);
		try {
			Properties props = new Properties();
			Session session = Session.getDefaultInstance(props, null);
			MimeMessage msg = new MimeMessage(session);
			msg.setFrom(new InternetAddress(fromEmail));
			
			msg.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
			msg.addRecipient(Message.RecipientType.BCC,new InternetAddress(fromEmail));
			
			msg.setSubject(subject, "UTF-8");
			msg.setContent(body, "text/html");
			Transport.send(msg);
			log.info("Send email success from " + fromEmail + " to " + toEmail + " with subject: " +subject);
		} catch (Exception e) {
			// TODO: handle exception
			log.warning("Send email unsuccess from " + fromEmail + " to " + toEmail + " with subject: " +subject);
			e.printStackTrace();
		}
	}
	
	public static void sendMailFromUrl(String fromEmail, String strSubject, String strUrl, String emails) {
		String strBody = StringHelper.getHtmlFromUrl(strUrl);//StringHelper.GetHtmlFromUrl(strUrl, "utf-8");

		try {
			String[] listEmail = emails.split(","); 
	
			Properties props = new Properties();
			Session session = Session.getDefaultInstance(props, null);
			MimeMessage msg = new MimeMessage(session);
			msg.setFrom(new InternetAddress(fromEmail));
			
			for (int i = 0; i < listEmail.length; i++) {
				if(i==0)
					msg.addRecipient(Message.RecipientType.TO, new InternetAddress(listEmail[i]));
				else
					msg.addRecipient(Message.RecipientType.BCC,new InternetAddress(listEmail[i]));
			}
			
			msg.setSubject(strSubject,"utf-8");
			msg.setContent(strBody, "text/html");
			Transport.send(msg);
		} catch (Exception e) {
			e.printStackTrace();
		}	
	}
	
	public static void main(String[] args) {
		String url = "http://www.orabuy.com/print/dealsemail/preview/RJOJ6UPK";
		String strBody = StringHelper.getHtmlFromUrl(url, "utf-8");
		System.out.println(strBody);
	}
}
